/*
 *  Copyright (C) 2010 Jonathan MERCIER <bioinfornatics@fedoraproject.org>,
 *  Louise-Amélie SCHMITT <louise-amelie.schmitt@etu.u-bordeaux1.fr>,
 *  Florence Maurier <florence_maurier@orange.fr>,
 *  Marianne Dussart <marianne.dussart@orange.fr>,
 *  Nicolas Fontaine <nifontaine@gmail.com>
 *
 *  JACoMode is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  JACoMode is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with JACoMode.  If not, see <http://www.gnu.org/licenses/>.
 */
package fr.ubdx1.jacomode.controller;

import fr.ubdx1.jacomode.models.AcomLaunch;
import fr.ubdx1.jacomode.models.Bilan;
import fr.ubdx1.jacomode.models.Tools;
import fr.ubdx1.jacomode.models.Compare;
import fr.ubdx1.jacomode.models.InputData;
import fr.ubdx1.jacomode.models.Results;
import fr.ubdx1.jacomode.models.BarChartModel;
import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Jonathan MERCIER <bioinfornatics@fedoraproject.org>,Louise-Amélie SCHMITT <louise-amelie.schmitt@etu.u-bordeaux1.fr>,Florence Maurier <florence_maurier@orange.fr>,Marianne Dussart <marianne.dussart@orange.fr>,Nicolas Fontaine <nifontaine@gmail.com>
 */
public class JACoMode extends HttpServlet
{

    private static final long                       serialVersionUID    = 4L;
    private static final    String                  BASE_DIRECTORY      = "/tmp/";
    private                 File                    userDirectories;
    private                 File                    fileOut;
    private                 File                    fileDat;
    private                 File                    acomDat;
    private                 File                    acomOut;
    private                 String                  epsilon;
    private                 String                  sigma;
    private                 String                  mail;
    private                 String                  rowNumber;
    private                 ArrayList<Integer>      idEfm;
    private                 ArrayList<Integer>      efmOccurence;
    private                 ArrayList<String>       efmlocation;
    private                 ArrayList<Integer>      sizeOfMotif;
    private                 ArrayList<Integer>      nbClassByMotifSize;
    private                 ArrayList<String>       iDClassByMotifSize;
    private                 ArrayList<File>         listCompareFile;
    private                 int                     classSize;
    private                 int                     nbClass;
    private                 int                     motifSize;
    private                 int                     nbMotifSize;
    private                 int                     meanMotif;
    private                 int                     totalefm;
    private                 String                  product;
    private                 String                  substrat;
    private                 Compare                 compare;
    private                 HashMap<Integer, String>epsilonSigma;
    private                 ArrayList<String>       motifsList;
    private                 BarChartModel           motifSizeChart;
    private                 BarChartModel           repeatChart;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession session = request.getSession(true);

        if (request.getRequestURI().equals("/JACoMode/acomForm"))
        {
            request.getRequestDispatcher("pages/acomForm.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/upload"))
        {

            session.invalidate();
            session = request.getSession(true);
            resetAttribute();
            doSessionDirectory(request, session);
            mail    = request.getParameter("email");
            epsilon = request.getParameter("epsilon");
            sigma   = request.getParameter("sigma");
            request.setAttribute("id",  session.getId());
            request.getRequestDispatcher("pages/upload.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/selectWichAcomSession"))
        {
            if ((fileDat == null) || (fileOut == null) || (epsilonSigma == null))
            {
                ArrayList<File> listFile    = doUpload(request, response);
                fileDat                     = listFile.get(0);
                fileOut                     = listFile.get(1);
                doAcom(request, response);
            }



            ArrayList<File> listCsv = Tools.listFileInDirectory(userDirectories, ".csv");
            listCompareFile         = listCsv;
            doComparisonResult(listCompareFile);
            if (compare.getEpsilon().isEmpty())
            {
                request.getRequestDispatcher("pages/nomotif.jsp").forward(request, response);
            }
            else
            {
                //System.err.println(compare.getEpsilon().get(0));
                request.setAttribute("total_class", compare.getTotalclass());
                request.setAttribute("total",       compare.getTotalefm());
                request.setAttribute("noise",       compare.getTotalnoise());
                request.setAttribute("epsilon",     compare.getEpsilon());
                request.setAttribute("sigma",       compare.getSigma());
                request.setAttribute("id",          session.getId());
                request.setAttribute("epsilonSigma", epsilonSigma);
                request.getRequestDispatcher("pages/selectWichAcomSession.jsp").forward(request, response);
            }
        }
        else if (request.getRequestURI().equals("/JACoMode/acomGlobalResults"))
        {
            doResult(request, response, session);
        }
        else if (request.getRequestURI().equals("/JACoMode/acomResultsByEFM"))
        {
            request.setAttribute("idEfm",           idEfm);
            request.setAttribute("efmOccurence",    efmOccurence);
            request.setAttribute("efmlocation",     efmlocation);
            request.getRequestDispatcher("pages/acomResultsByEFM.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/acomResultsByMotifSize"))
        {
            request.setAttribute("sizeOfMotif",         sizeOfMotif);
            request.setAttribute("nbClassByMotifSize",  nbClassByMotifSize);
            request.setAttribute("IDClassByMotifSize",  iDClassByMotifSize);
            request.setAttribute("meanMotif",           meanMotif);
            request.setAttribute("nbMotifSize",         nbMotifSize);
            request.getRequestDispatcher("pages/acomResultsByMotifSize.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/download.tar.bz2"))
        {
            doDownload(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/error"))
        {
            String errors = (String) request.getAttribute("errors");
            request.setAttribute("errors", errors);
        }
        else if (request.getRequestURI().equals("/JACoMode/bilanForm"))
        {
            request.getRequestDispatcher("pages/bilanForm.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/bilanResult"))
        {
            session.invalidate();
            session = request.getSession(true);
            resetAttribute();
            doSessionDirectory(request, session);
            ArrayList<File> listFile    = doUpload(request, response);
            fileOut                     = listFile.get(0);
            doOverallResult(request, fileOut, session);
            request.setAttribute("id",  session.getId());
            request.getRequestDispatcher("pages/bilanResult.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/bilanArchiveCompare"))
        {
            Enumeration enumeration = request.getParameterNames();
            ArrayList<File>     listCsv     = new  ArrayList<File>();
            while(enumeration.hasMoreElements())
            {
                String key = (String)enumeration.nextElement();
                if(request.getParameter(key).equals("on"))
                {
                    System.err.println("clé: "+key);
                    listCsv.add(new File(key));
                }
            }
            listCompareFile = listCsv;
            doComparisonResult(listCompareFile);
            request.setAttribute("total_class", compare.getTotalclass());
            request.setAttribute("total",       compare.getTotalefm());
            request.setAttribute("noise",       compare.getTotalnoise());
            request.setAttribute("epsilon",     compare.getEpsilon());
            request.setAttribute("sigma",       compare.getSigma());
            request.setAttribute("id",          session.getId());
            request.getRequestDispatcher("pages/compareResult.jsp").forward(request, response);


        }
        else if (request.getRequestURI().equals("/JACoMode/compareForm"))
        {
            request.getRequestDispatcher("pages/compareForm.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/compareResult"))
        {
            session.invalidate();
            resetAttribute();
            session = request.getSession(true);
            doSessionDirectory(request, session);
            ArrayList<File> listFile    = doUpload(request, response);
            listCompareFile = listFile;
            doComparisonResult(listCompareFile);
            request.setAttribute("total_class", compare.getTotalclass());
            request.setAttribute("total",       compare.getTotalefm());
            request.setAttribute("noise",       compare.getTotalnoise());
            request.setAttribute("epsilon",     compare.getEpsilon());
            request.setAttribute("sigma",       compare.getSigma());
            request.setAttribute("id",          session.getId());
            request.getRequestDispatcher("pages/compareResult.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/bilanSearch"))
        {
            doOverallSearch(request, response);
            request.getRequestDispatcher("pages/bilanSearch.jsp").forward(request, response);
        }
        else if(request.getRequestURI().equals("/JACoMode/selectCSV"))
        {
            session.invalidate();
            resetAttribute();
            session = request.getSession(true);
            doSessionDirectory(request, session);
            ArrayList<File> listArchiveFile = doUpload(request, response);
            System.err.println("taille: " +listArchiveFile.size());
            Iterator iterator = listArchiveFile.iterator();
            while(iterator.hasNext())
            {
                File file = (File) iterator.next();
                try
                {System.err.println("fichier: " +file.getAbsolutePath());
                    Tools.decompress(file.getAbsolutePath(), userDirectories.getAbsolutePath());
                }
                catch (InterruptedException ex)
                {
                    Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, ex);
                    request.setAttribute("errors", "Error with Compression ==> " + ex.getCause() + "   Message: " + ex.getMessage() + "    Trace: " + ex.getStackTrace());
                    request.getRequestDispatcher("pages/error.jsp").forward(request, response);
                    return;
                }
            }
            ArrayList<File> listCsvFile = Tools.listFileInDirectory(userDirectories, ".csv");
            System.err.println("nb: " +listCsvFile.size());
            request.setAttribute("listCsvFile", listCsvFile);
            request.setAttribute("id",          session.getId());
            request.getRequestDispatcher("pages/selectCSV.jsp").forward(request, response);
        }
        else if (request.getRequestURI().equals("/JACoMode/resultTable"))
        {
            request.setAttribute("epsilonSigma", epsilonSigma);
            request.getRequestDispatcher("pages/resultTable.jsp").forward(request, response);
        }
        else
        {
            request.setAttribute("errors", "Unknow web page " + request.getRequestURI());
            request.getRequestDispatcher("pages/error.jsp").forward(request, response);
        }

    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Launch ACoM
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void doAcom(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            if (!fileDat.exists())
            {
                throw new Exception(fileDat.getAbsolutePath());
            }
            else if (!fileOut.exists())
            {
                throw new Exception(fileDat.getAbsolutePath());
            }
        }
        catch (Exception e)
        {
            request.setAttribute("errors", "Error with " + e + " file do not exist!");
            Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, e);
            return;
        }

        HttpSession session         = request.getSession(true);
        String      id;
        String[]    epsilonArray    = epsilon.split("-");
        String[]    sigmaArray      = sigma.split("-");
        String      epsilonStart    = "";
        String      epsilonEnd      = "";
        String      sigmaStart      = "";
        String      sigmaEnd        = "";

        if (epsilonArray.length == 1)
        {
            epsilonStart    = epsilonArray[0];
            epsilonEnd      = epsilonArray[0];
        }
        else
        {
            epsilonStart    = epsilonArray[0];
            epsilonEnd      = epsilonArray[1];
        }

        if (sigmaArray.length == 1)
        {
            sigmaStart  = sigmaArray[0];
            sigmaEnd    = sigmaArray[0];
        }
        else
        {
            sigmaStart  = sigmaArray[0];
            sigmaEnd    = sigmaArray[1];
        }

        int num = 0;
        epsilonSigma = new HashMap<Integer, String>();

        for (int i = Integer.parseInt(epsilonStart); i <= Integer.parseInt(epsilonEnd); i++)
        {
            for (int j = Integer.parseInt(sigmaStart); j <= Integer.parseInt(sigmaEnd); j++)
            {
                id                  = session.getId()+num;
                File acomdirectory  = new File(userDirectories + "/" + num);
                acomdirectory.mkdir();
                acomDat             = new File(acomdirectory + "/acom.dat");
                acomOut             = new File(acomdirectory + "/acom.out");
                System.err.println("ep: "+i+" sig:"+j);
                System.err.println("fileDat: "  + fileDat.exists());
                System.err.println("fileOut: "  + fileOut.exists());
                InputData data      = new InputData(fileDat.getAbsolutePath(), fileOut.getAbsolutePath(), acomDat.getAbsolutePath(), acomOut.getAbsolutePath());
                rowNumber           = Integer.toString(data.getdoutListsize());
                System.err.println("acomDat: "  + acomDat.exists());
                System.err.println("acomOut: "  + acomOut.exists());
                System.err.println("ligne: "    + rowNumber);
                try
                {
                    AcomLaunch acomExec = AcomLaunch.getAcom(id, mail, acomOut, acomDat, rowNumber, Integer.toString(i),  Integer.toString(j) );
                    acomExec.exec(acomdirectory.getPath()); //userDirectories.getPath()
                    System.err.println("acom is finished");
                }
                catch (InterruptedException ex)
                {
                    request.setAttribute("errors", "Error with AcomLaunch ==> " + ex.getCause() + "   Message: " + ex.getMessage() + "    Trace: " + ex.getStackTrace());
                    Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, ex);
                    return;
                }
                catch (Exception e)
                {
                    request.setAttribute("errors", "Error with Result ==> " + e.getCause() + "   Message: " + e.getMessage() + "    Trace: " + e.getStackTrace());
                    return;
                }
                epsilonSigma.put(num, Integer.toString(i) + " - " + Integer.toString(j));

                File motif = new File(acomdirectory + "/motif.txt");
                if (motif.exists()) {
                    Results csv = new Results();
                    csv.parse(acomdirectory.getPath());
                    csv.csvResult(j, i, acomdirectory.getPath()+ "/", num);
                }
                num++;
            }
        }
        String bzipFileName = userDirectories.getAbsolutePath().substring(0, userDirectories.getAbsolutePath().length()) + ".tar.bz2";
        try
        {
            Tools.compress(bzipFileName, userDirectories.getAbsolutePath());
        }
        catch (InterruptedException ex)
        {
            request.setAttribute("errors", "Error with Compression ==> " + ex.getCause() + "   Message: " + ex.getMessage() + "    Trace: " + ex.getStackTrace());
            Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
        catch (Exception e)
        {
            request.setAttribute("errors", "Error with Compression ==> " + e.getCause() + "    Message: " + e.getMessage() + "    Trace: " + e.getStackTrace());
            return;
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }

    /**
     * Process download
     * @param response servlet response
     * @param request servlet request
     */
    private void doDownload(HttpServletRequest request, HttpServletResponse response)
    {
        //get the 'file' name
        String fileName             = userDirectories.getAbsolutePath() + ".tar.bz2";
        ServletOutputStream stream  = null;
        BufferedInputStream buffer  = null;

        try
        {
            stream = response.getOutputStream();
            buffer = new BufferedInputStream(new FileInputStream(fileName));
            int readBytes = 0;
            //read from the file; write to the ServletOutputStream
            while ((readBytes = buffer.read()) != -1)
            {
                stream.write(readBytes);
            }
        }
        catch (IOException e)
        {
            request.setAttribute("errors", "Error in download " + e.getStackTrace());
        }
    }

    /**
     * Process analysis of Overall Reaction
     * @param response servlet response
     * @param request servlet request
     */
    private void doOverallResult(HttpServletRequest request, File file, HttpSession session)
    {
        try
        {
            System.err.println("doOverallResult");
            Bilan bilan = new Bilan();
            bilan.addBilan(file.getAbsolutePath());
            System.err.println("doBilan");
            session.setAttribute("bilan",           bilan);
            session.setAttribute("name",            fileOut.getName());
            request.setAttribute("inner",           bilan.getBilansin());
            request.setAttribute("outer",           bilan.getBilansout());
            request.setAttribute("nb_EFM",          bilan.getBilanssame4());
            request.setAttribute("numero_EFM",      bilan.getBilanssame2());
            session.setAttribute("inner_choice",    bilan.getMetaboIn());
            session.setAttribute("outer_choice",    bilan.getMetaboOut());
        }
        catch (Exception e)
        {
            request.setAttribute("errors", "Error in OverallResult ==> " + e.getStackTrace());
        }
    }

    /**
     * Process analysis of Overall Reaction by search
     * @param response servlet response
     * @param request servlet request
     */
    public void doOverallSearch(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            HttpSession session = request.getSession();
            Bilan bilan         = (Bilan) session.getAttribute("bilan");
            product             = request.getParameter("productlist");
            substrat            = request.getParameter("substratlist");
            session.setAttribute("product", product);
            session.setAttribute("substrat", substrat);
            bilan.metabolite(substrat);
            bilan.metabolite(product);
            bilan.clean();
            bilan.metabolite(substrat);
            bilan.metabolite(product);
            request.setAttribute("inner", bilan.getMetabobilansin());
            request.setAttribute("outer", bilan.getMetabobilansout());
            request.setAttribute("nb_efm", bilan.getMetaboefm());
        }
        catch (Exception ex)
        {
            Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("errors", "Error in OverallSearch ==> " + ex.getMessage());
        }
    }

    /**
     * Process analysis of comparison files
     * @param listFile list containing files
     */
    public void doComparisonResult(ArrayList<File> listFile)
    {
        compare = new Compare();
        Iterator iterator = listFile.iterator();
        while (iterator.hasNext())
        {
            File file = (File) iterator.next();
            System.err.println("Boucle comparaison: "+file.getAbsolutePath());
            compare.addComparaisonFile(file.getAbsolutePath());
        }
    }


    /**
     * Process upload
     * @param response servlet response
     * @param request servlet request
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     * @return listFile list containing files
     */
    public ArrayList<File> doUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        ArrayList<File> listFile = new ArrayList<File>();

        // check if the http request is a multipart request
        // with other words check that the http request can have uploaded files
        if (isMultipart)
        {
            //  Create a factory for disk-based file items
            //FileItemFactory factory = new DiskFileItemFactory();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(51200);//50Kio
            factory.setRepository(userDirectories);


            //  Create a new file upload handler
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            // Set upload parameters
            // See Apache Commons FileUpload for more information
            // http://jakarta.apache.org/commons/fileupload/using.html
            servletFileUpload.setSizeMax(104857600);
            servletFileUpload.setFileSizeMax(52428800);

            try
            {
                String directory = "";
                // Parse the request
                List fileItems = servletFileUpload.parseRequest(request);

                Iterator itr = fileItems.iterator();
                while (itr.hasNext())
                {
                    FileItem item = (FileItem) itr.next();

                    // the param tag directory is sent as a request parameter to
                    // the server
                    // check if the upload directory is available

                    if (item.isFormField())
                    {
                        //System.out.println(item.getOutputStream().toString());if (name.equalsIgnoreCase("directory"))
                        {
                            directory = item.getString();
                        }
                    }
                    else
                    {
                        // the fileNames are urlencoded
                        String fileName = URLDecoder.decode(item.getName(), "UTF-8");

                        File file = new File(directory, fileName);
                        file = new File(userDirectories.getAbsoluteFile(), file.getPath());
                        // retrieve the parent file for creating the directories
                        File parentFile = file.getParentFile();

                        if (parentFile != null)
                        {
                            parentFile.mkdirs();
                        }

                        // writes the file to the filesystem
                        item.write(file);
                        listFile.add(file);
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                request.setAttribute("errors", "Error in ACoMGlobalResults ==> " + e.getCause() + "   Message: " + e.getMessage() + "    Trace: " + e.getStackTrace());
                request.getRequestDispatcher("pages/error.jsp").forward(request, response);
                return null;
            }
            catch (Exception e)
            {
                request.setAttribute("errors", "Error in ACoMGlobalResults ==> " + e.getCause() + "   Message: " + e.getMessage() + "    Trace: " + e.getStackTrace());
                request.getRequestDispatcher("pages/error.jsp").forward(request, response);
                return null;
            }
        }
        else
        {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        return listFile;
    }

    /**
     * Process session directory
     * @param request servlet request
     */
    private void doSessionDirectory(HttpServletRequest request, HttpSession session)
    {
        if ((userDirectories == null) || (!userDirectories.exists()))
        {
            userDirectories = new File(BASE_DIRECTORY + session.getId() + "/");
            userDirectories.mkdir();
            userDirectories.setWritable(true);
            userDirectories.setReadable(true);
        }
    }

    /**
     * Process result ACoM
     * @param response servlet response
     * @param request servlet request
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private void doResult(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException
    {

        String  acomSession     = new String();
        if (request.getParameter("acomSession") != null)
        {
            acomSession = request.getParameter("acomSession");
            session.setAttribute("acomSession", acomSession);
        }
        else
        {
            acomSession = (String) session.getAttribute("acomSession");
        }
        int     epsilonInt      = Integer.parseInt(String.valueOf(epsilonSigma.get(Integer.parseInt(acomSession)).charAt(0)));
        int     sigmaInt        = Integer.parseInt(String.valueOf(epsilonSigma.get(Integer.parseInt(acomSession)).charAt(epsilonSigma.get(Integer.parseInt(acomSession)).length() - 1)));
        File    acomDirectory   = new File(userDirectories  + "/" + acomSession);
        File    motif           = new File(acomDirectory    + "/motif.txt");
        if (motif.exists())
        {
            try
            {
                Results stat = new Results();
                stat.parse(acomDirectory.getAbsolutePath());

                idEfm               = stat.getIDEfm();
                efmOccurence        = stat.getEfmOccurence();
                efmlocation         = stat.getEfmLocation();
                sizeOfMotif         = stat.getSizeOfMotif();
                nbClassByMotifSize  = stat.getNbClassByMotifSize();
                iDClassByMotifSize  = stat.getIDClassByMotifSize();
                classSize           = stat.getMeanClassSize();
                nbClass             = stat.getNbtotalClass();
                motifSize           = stat.getMeanMotifSize();
                nbMotifSize         = stat.getNbOfDifferentMotifSize();
                meanMotif           = stat.getMeanMotifSize();
                totalefm            = stat.getTotalefm();
                motifsList          = stat.getMotif();

                request.setAttribute("fileDat",         fileDat);
                request.setAttribute("fileOut",         fileOut);
                request.setAttribute("epsilon",         epsilonInt);
                request.setAttribute("sigma",           sigmaInt);
                request.setAttribute("class_size",      classSize);
                request.setAttribute("nb_class",        nbClass);
                request.setAttribute("motif_size",      motifSize);
                request.setAttribute("nb_motif_size",   nbMotifSize);
                request.setAttribute("nb_motif",        meanMotif);
                request.setAttribute("totalefm",        totalefm);
                request.setAttribute("motifs",        motifsList);
            }
            catch (NullPointerException npe)
            {
                request.setAttribute("errors", "Error with Result ==> " + npe.getCause() + "   Message: " + npe.getMessage() + "    Trace: " + npe.getStackTrace());
                Logger.getLogger(JACoMode.class.getName()).log(Level.SEVERE, null, npe);
            }
            catch (Exception e)
            {
                request.setAttribute("errors", "Error with Result ==> " + e.getCause() + "   Message: " + e.getMessage() + "    Trace: " + e.getStackTrace());
            }
        }
        else
        {
            request.setAttribute("fileDat",         fileDat);
            request.setAttribute("fileOut",         fileOut);
            request.setAttribute("epsilon",         epsilonInt);
            request.setAttribute("sigma",           sigmaInt);
            request.setAttribute("class_size",      null);
            request.setAttribute("nb_class",        null);
            request.setAttribute("motif_size",      null);
            request.setAttribute("nb_motif_size",   null);
            request.setAttribute("nb_motif",        null);
        }
        request.getRequestDispatcher("pages/acomGlobalResults.jsp").forward(request, response);
    }

    private void resetAttribute()
    {
        userDirectories     = null;
        fileOut             = null;
        fileDat             = null;
        acomDat             = null;
        acomOut             = null;
        epsilon             = new String();
        sigma               = new String();
        mail                = new String();
        rowNumber           = new String();
        idEfm               = new ArrayList<Integer>();
        efmOccurence        = new ArrayList<Integer>();
        efmlocation         = new ArrayList<String>();
        sizeOfMotif         = new ArrayList<Integer>();
        nbClassByMotifSize  = new ArrayList<Integer>();
        iDClassByMotifSize  = new ArrayList<String>();
        listCompareFile     = new ArrayList<File>();
        classSize           = 0;
        nbClass             = 0;
        motifSize           = 0;
        nbMotifSize         = 0;
        meanMotif           = 0;
        totalefm            = 0;
        product             = new String();
        substrat            = null;
        compare             = new Compare();
        epsilonSigma        = new HashMap<Integer, String>();
    }
}